package com.bluefoxyu.impl;

import com.bluefoxyu.game.Direction;
import com.bluefoxyu.game.GameMap;
import com.bluefoxyu.service.SnakeGameService;
import com.bluefoxyu.util.SnowflakeIdGenerator;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class SnakeGameServiceImpl implements SnakeGameService {
    private static final Map<String, GameMap> gameMapRegistry = new HashMap<>();

    /**
    * <p>
    * Description: 初始化地图
    * </p>
    *
    * @return: java.lang.String 返回该用户的sessionId ,目前用map来做，后续可以改善为redis
    * @Author: bluefoxyu
    * @Date: 2025-05-27 00:03:47
    */
    @Override
    public String startGame() {
//        String sessionId = UUID.randomUUID().toString(); // UUID 生成session
        String sessionId = String.valueOf(new SnowflakeIdGenerator(1, 1).nextId()); // 雪花算法生成session
        GameMap gameMap = new GameMap(20, 10);
        gameMapRegistry.put(sessionId, gameMap);
        gameMap.render(sessionId);
        return sessionId;
    }

    @Override
    public GameMap getMap(String sessionId) {
        return gameMapRegistry.get(sessionId);
    }

    /**
    * <p>
    * Description:
    * </p>
    *
    * @param sessionId 用户sessionId
    * @param direction 移动的操作
    * @return: void
    * @Author: bluefoxyu
    * @Date: 2025-05-27 00:04:40
    */
    @Override
    public void move(String sessionId, Direction direction) {
        GameMap gameMap = gameMapRegistry.get(sessionId);
        try {
            if (gameMap == null) {
                System.out.println("游戏未开始，请先调用 startGame 方法。");
                return;
            }
            gameMap.update(direction);
            gameMap.render(sessionId);
        } catch (Exception e) {
            System.out.println("游戏结束: " + e.getMessage());
            System.exit(0);
        }
    }

    public void clearGameMap(String sessionId) {
        gameMapRegistry.remove(sessionId);
    }
}